<template>
  <NewCard :title="recordState ? '资金明细' : '账户提现'">
    <!-- 资金明细 -->
    <div class="detail" v-if="recordState">
      <!-- 表单 -->
      <el-form ref="form" :inline="true">
        <el-form-item label="时间">
          <el-date-picker
            @change="getMonth"
            type="month"
            value-format="yyyy-MM"
            size="small"
            v-model="month"
            placeholder="选择月份"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="currentValue"
            size="small"
            @change="selectTypeFn"
            placeholder="请选择"
          >
            <el-option label="全部" :value="null"> </el-option>
            <el-option label="收入" value="1"> </el-option>
            <el-option label="支出" value="2"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentState" size="small" placeholder="请选择">
            <!-- 收入：不可提现/未提现/已提现  支出：出账中/已到账 -->
            <el-option label="全部" :value="null"> </el-option>
            <el-option label="提现失败" value="-1"> </el-option>
            <el-option label="未提现" value="0"> </el-option>
            <el-option label="出账中" value="1"> </el-option>
            <el-option label="已提现" value="2"> </el-option>
            <el-option label="不可提现" value="3"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button round class="inquire" @click="inquireFn">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table
        v-loading="isLoad"
        :data="tableData"
        style="width: 100%"
        @expand-change="expandSelect"
        :expand-row-keys="expands"
        :row-key="getRowKeys"
      >
        <el-table-column
          prop="type"
          :formatter="formatterFn"
          label="资金类型"
          width="100"
        >
        </el-table-column>
        <el-table-column prop="title" label="订单名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <p v-if="scope.row.type == '1'">{{ scope.row.title }}</p>
            <p v-else>账户提现</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="payTime"
          label="时间"
          width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <p>{{ getCreateTime(scope.row) }}</p>
          </template>
        </el-table-column>
        <el-table-column align="right" prop="amount" label="金额" width="100">
          <template slot-scope="scope">
            <p v-if="scope.row.type == '1'">
              +{{ getAmount(scope.row) | sumFilters }}
            </p>
            <p v-else>-{{ getAmount(scope.row) | sumFilters }}</p>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="right" width="100">
          <template slot-scope="scope">
            <span>{{ getState(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="查看明细"
          width="80"
          align="right"
          type="expand"
        >
          <template slot-scope="props">
            <!-- type=1是收入 -->
            <div class="orderDetail" v-if="props.row.type == '1'">
              <div v-if="unfoldInfo && unfoldInfo.id">
                <h3>订单编号：{{ unfoldInfo.orderId }}</h3>
                <ul>
                  <!-- 商务专员 -->
                  <li v-if="userRole.cmId && userRole.cmId == unfoldInfo.cmId">
                    商务专员：¥{{ unfoldInfo.cmCommission | sumFilters }}
                  </li>
                  <!-- 商务经理 -->
                  <li
                    v-if="
                      userRole.cmId && userRole.cmId == unfoldInfo.cmDirectorId
                    "
                  >
                    商务经理：¥{{ unfoldInfo.cmDirector | sumFilters }}
                  </li>
                  <!-- 商务总监 -->
                  <li
                    v-if="
                      userRole.cmId &&
                      userRole.cmId == unfoldInfo.cmSupervisorId
                    "
                  >
                    商务总监：¥{{ unfoldInfo.cmSupervisor | sumFilters }}
                  </li>
                  <!-- 渠道专员 -->
                  <li
                    v-if="
                      userRole.placeId && userRole.placeId == unfoldInfo.placeId
                    "
                  >
                    渠道专员：¥{{ unfoldInfo.placeCommission | sumFilters }}
                  </li>
                  <!-- 渠道经理 -->
                  <li
                    v-if="
                      userRole.placeId &&
                      userRole.placeId == unfoldInfo.placeDirectorId
                    "
                  >
                    渠道经理：¥{{ unfoldInfo.placeDirector | sumFilters }}
                  </li>
                  <!-- 渠道总监 -->
                  <li
                    v-if="
                      userRole.placeId &&
                      userRole.placeId === unfoldInfo.placeSupervisorId
                    "
                  >
                    渠道总监：¥{{ unfoldInfo.placeSupervisor | sumFilters }}
                  </li>
                  <!-- 专家分成 -->
                  <!-- 专家分成如果有更新时间update_time就显示verify_amount字段，没有就显示unfoldInfo.expertCommission -->
                  <li
                    v-if="
                      userRole.expertId &&
                      userRole.expertId == unfoldInfo.expertId
                    "
                  >
                    专家分成：¥{{ getExpertAmount(props.row) | sumFilters }}
                  </li>
                  <!-- <li>实体拨比：¥{{unfoldInfo.organizationCommission | sumFilters}}</li> -->
                  <!-- 实体收款人拨比 -->
                  
                  <li v-if="userRole.paymentId && (userRole.paymentId == unfoldInfo.paymentId)">实体收款人拨比：¥{{unfoldInfo.organizationCommission | sumFilters}}</li>

                  <!-- 管拨收款人拨比 -->
                  <li v-if="userRole.operationsId && (userRole.operationsId == unfoldInfo.operationsId)">管拨收款人拨比：¥{{unfoldInfo.operations | sumFilters}}</li>
                </ul>
              </div>
              <div v-else>
                <i class="el-icon-loading" v-if="infoLoadShow"></i>
                <p class="noData-p" v-else>暂无数据</p>
              </div>
            </div>
            <!-- type=2是支出 -->
            <div class="orderDetail" v-else>
              <p>
                提现账户：{{ props.row.bank }}（{{
                  props.row.card_no.substring(props.row.card_no.length - 4)
                }}）
              </p>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部统计 -->
      <SubBtn>
        <template slot="btn">
          <p class="bottomStatistics">{{ getSelectDate() }}</p>
          <p class="bottomStatistics">
            收入¥{{ getAllIncome() }}，支出¥{{ getAllExpend() }}
          </p>
        </template>
      </SubBtn>
    </div>

    <!-- 账户提现 -->
    <div class="withdraw" v-else>
      <el-form ref="form" label-width="130px" label-position="left">
        <el-form-item label="提现至">
          <el-select
            v-model="withdraw.bankcardId"
            @change="getSelectFn"
            placeholder="请选择银行卡"
          >
            <el-option
              :value="item.id || 0"
              :label="getWithName(item)"
              v-for="(item, index) in cardList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可用余额">
          ￥{{ canwithdrawMoney | sumFilters }}
        </el-form-item>
        <el-form-item label="提现金额">
          <el-input
            readonly
            @click.native="addWithdrawAmount"
            v-model="withdraw.amount"
            placeholder="请选择提现订单"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          {{ getPhone }}
        </el-form-item>
        <el-form-item label="验证码">
          <el-input
            v-model="verifyObj.code"
            @blur="verifyObjFn"
            placeholder="请输入验证码"
          >
            <el-button @click="obtainVerifyCode" slot="suffix"
              ><span
                :style="{
                  color: verifyContent.disabled ? 'grey' : '#f87a23',
                  cursor: verifyContent.disabled ? 'unset' : 'pointer',
                }"
              >
                {{ verifyContent.disabled ? verifyContent.text : "获取验证码" }}
              </span></el-button
            >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="withdrawBtn">
        <!-- <el-button round>取消</el-button> -->
        <el-button
          round
          class="addBtn"
          @click="clickWithdrawFn"
          :class="{ canwithdraw: !verifyContentBtn }"
          >申请提现</el-button
        >
      </div>
    </div>
    <WithdrawOrder
      ref="withDrawOrder"
      :userRole="userRole"
      :WithdrawalList="WithdrawalList"
      @EventGetAllMoney="GetAllMoney"
      @EventScrollLoadMore="scrollLoadMore"
      :isOpen.sync="isOpenWithdrawOrder"
      :total="pageing.total"
    ></WithdrawOrder>
  </NewCard>
</template>

<script>
import { amend } from "@/wss/utils/wss.js";
import { debounce, toDecimal } from "@/wss/utils/wss.js";
import { getExpertBrokerageAddApi } from "@/BMViews/api/financial/expertBrokerage.js";
import { getConfigWithdrawSettingApi } from "@/BMViews/api/base/config.js";
import { getCmBrokerageAddApi } from "@/BMViews/api/financial/cmBrokerage.js";
import { getCmBrokerageListApi } from "@/BMViews/api/financial/cmBrokerage.js";
import { getExpertBrokeragelistApi } from "@/BMViews/api/financial/expertBrokerage.js";
import { getSelectUserOrderApi } from "@/BMViews/api/service/circle.js";
import {
  getOrderCommissionIncomeExpenditureApi,
  getOrderCommissionListApi,
  getIOrderCommissionWithdrawApi,
  getOrderCommissionWithdrawApi,
  getOrderCommissionUserWithdrawalApi,
  getCommercialManagerWithdrawalApi,
  getCommercialEntityWithdrawalApi,
  getExpertWithdrawalApi
} from "@/BMViews/api/financial/orderCommission.js";
import { updateGetRoleIdApi } from "@/api/system/user.js";
import { getMobileUserBalanceApi } from "@/BMViews/api/financial/orderCommission.js";
import {
  getOrderListApi,
  getVerificationCodeApi,
} from "@/BMViews/api/login.js";
import NewCard from "@/wss/components/newCard.vue";
import WithdrawOrder from "./withdrawOrder.vue";
import SubBtn from "@/components/subBtn/subBtn.vue";
import lodebounce from "lodash/debounce";
export default {
  name: "DetailOrWithdraw",
  components: { NewCard, WithdrawOrder, SubBtn },
  props: {
    recordState: {
      type: Boolean,
      default: false,
    },
    amount: {
      type: [String, Number],
      default: 0,
    },
    cardList: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  async mounted() {
    await this.updateGetRoleIdFn();
    this.getConfigWithdrawSettingFn();
    this.getMobileUserBalance() //查询可提现金额

    this.positionType = this.$store.state.user.userType;
    this.getOrderCommissionIncomeExpenditure(); //收入支出明细列表
    // this.getOrderCommissionUserWithdrawalFn();

    this.verifyObj.mobile = this.$store.state.user.phonenumber; //电话

    // if (this.positionType == 50) {
    //   this.getExpertBrokeragelistFn();
    // } else if (this.positionType == 60) {
    //   this.getCmBrokerageListFn();
    // }
  },
  computed: {
    getPhone() {
      // console.log(this.$store.getters);
      return (
        this.$store.state.user.phonenumber.slice(0, 3) +
        "****" +
        this.$store.state.user.phonenumber.slice(-3)
      );
    },
  },
  data() {
    return {
      // ----------------资金账户----------------
      // 分页参数
      pageing:{pageNum:1,pageSize:10,total:0,},
      month: this.getTime(), //选择的月份
      currentValue: null, //类型
      currentState: null, //状态
      expands: [], //资金账户展开行

      // 流水账参数
      accountObj: {
        bank: null, // 银行	query	false
        cardNo: null, // 银行卡号	query	false
        cmId: null, // 商务id	query	false
        userType: null,
        createTime: null, // 创建时间	query	false
        orderId: null, // 1为用户调用	query	false
        status: null, // 状态	query	false
        type: null, // 类型	query	false
      },

      unfoldInfo: {}, //当前展开的详细信息
      infoLoadShow: false, //加载圈圈显示隐藏
      // ----------------资金账户----------------end

      verifyContentBtn: false, // 验证验证码是否通过，没有提现按钮点击不了
      positionType: "", //当前的用户类型userType
      userRole: {}, // 当前用户的提现角色
      isLoad: false,

      // 最低提现额度
      w_min_money: "",
      // 最高提现金额
      w_max_money: "",
      verifyObj: {
        // 验证码
        code: "",
        // 手机号
        mobile: "",
      },
      // 获取验证码按钮
      verifyContent: {
        disabled: false,
        text: "获取验证码",
        time: 60,
      },
      withdraw: {
        bankcardId: this.cardList[0]?.id,
        list: [],
        // 提现金额
        amount: "",
      },
      // 可提现的所有金额
      canwithdrawMoney: 0,
      tableData: [],
      // 是否显示提现选择订单
      isOpenWithdrawOrder: false,

      // 提现的订单列表
      WithdrawalList: [],
      // 收集到的订单列表
      withdrawalOrderList: [],
    };
  },
  methods: {
    // ----------------------------------------资金账户----------------------------------------
    // 资金账户列表
    // async getSelectUserOrderFn() {
    //   let { code, rows } = await getSelectUserOrderApi();
    //   if (code != 200) return;
    //   this.tableData = JSON.parse(JSON.stringify(rows));
    // },

    // 收入支出明细列表
    async getOrderCommissionIncomeExpenditure(createTime, type, status) {
      let params = {
        createTime: this.month,
      };
      if (createTime) params.createTime = createTime;
      if (type) params.type = type;
      if (status) params.status = status;

      let result = await getOrderCommissionIncomeExpenditureApi(params);
      if (result.code != 200) return;
      this.tableData = JSON.parse(JSON.stringify(result.rows));
    },

    // 当前月发生改变
    getMonth(date) {
      this.month = date;
      this.accountObj.pcCreateTime = date;
    },
    // 选择流水账的类型
    selectTypeFn(type) {
      this.accountObj.type = type;
    },
    // 查询流水账函数
    inquireFn() {
      let createTime = this.month;
      let type = this.currentValue; //类型
      let status = this.currentState; //状态
      this.getOrderCommissionIncomeExpenditure(createTime, type, status);
    },
    // 过滤函数
    formatterFn(row) {
      return row.type == "1" ? "收入" : "支出";
    },
    // 专家流水账
    async getExpertBrokeragelistFn() {
      let { code, rows } = await getExpertBrokeragelistApi(this.accountObj);
      if (code != 200) return;
      this.tableData = JSON.parse(JSON.stringify(rows));
      this.isLoad = false;
    },
    // 获取商务流水账
    async getCmBrokerageListFn() {
      let { code, rows } = await getCmBrokerageListApi(this.accountObj);
      if (code != 200) return;
      this.tableData = JSON.parse(JSON.stringify(rows));
      this.isLoad = false;
    },

    // 一次只能展开一行
    expandSelect(row, expandedRows) {
      this.unfoldInfo = {}; // 获取前先清除之前的
      this.getOrderCommissionList(row.order_id); //获取展开详情的接口

      let that = this;
      if (expandedRows.length) {
        that.expands = [];
        if (row) {
          that.expands.push(row.id);
        }
      } else {
        that.expands = [];
      }
    },
    // 一次只能展开一行
    getRowKeys(row) {
      return row.id;
    },

    // 获取当前时间
    getTime() {
      let date = new Date();
      let moon = date.getMonth() + 1;
      let year = date.getFullYear();
      if (moon > 9) {
        return year + "-" + moon;
      } else {
        return year + "-0" + moon;
      }
    },

    // 获取时间
    getCreateTime(row) {
      let arr = [];
      if (row.verify_amount) {
        // 有verify_amount字段的时候展示更新时间
        arr = row.update_time;
      } else {
        // 没有verify_amount字段展示创建时间
        arr = row.create_time;
      }
      if (arr && arr.length > 0) {
        // 年
        let year = "00";
        if (arr[0]) {
          year = arr[0].toString().substring(2, 4);
        }
        // 月
        let moon = "00";
        if (arr[1]) {
          moon = arr[1] > 9 ? arr[1].toString() : "0" + arr[1].toString();
        }
        // 日
        let day = "00";
        if (arr[2]) {
          day = arr[2] > 9 ? arr[2].toString() : "0" + arr[2].toString();
        }
        // 时
        let hour = "00";
        if (arr[3]) {
          hour = arr[3] > 9 ? arr[3].toString() : "0" + arr[3].toString();
        }
        // 分
        let minute = "00";
        if (arr[4]) {
          minute = arr[4] > 9 ? arr[4].toString() : "0" + arr[4].toString();
        }
        // 秒
        let second = "00";
        if (arr[5]) {
          second = arr[5] > 9 ? arr[5].toString() : "0" + arr[5].toString();
        }
        return year + moon + day + " " + hour + ":" + minute + ":" + second;
      }
    },

    // 获取底部时间
    getSelectDate() {
      let date = this.month.split("-");
      return date[0] + "年" + date[1] + "月";
    },

    // 获取总收入 1收入 2支出
    getAllIncome() {
      let all = 0;
      let arr = this.tableData.filter((item) => {
        return item.type == "1";
      });
      arr.forEach((item) => {
        if (item.status != "3") {
          all = amend(item.amount, all);
        }
      });
      return this.$options.filters["sumFilters"](all);
    },

    // 获取总支出 1收入 2支出
    getAllExpend() {
      let all = 0;
      let arr = this.tableData.filter((item) => {
        return item.type == "2";
      });
      arr.forEach((item) => {
        if (item.status != "-1") {
          all = amend(item.amount, all);
        }
      });
      return this.$options.filters["sumFilters"](all);
    },

    // 获取状态 收入：不可提现/未提现/已提现  支出：出账中/已到账
    getState(row) {
      // 1收入 2支出
      if (row.type == "1") {
        const stateMap = {
          "-1": "提现失败",
          0: "未提现",
          1: "提现中",
          2: "已提现",
          3: "不可提现",
        };
        return stateMap[row.status];
      } else {
        const stateMap = {
          "-1": "提现失败",
          1: "出账中",
          2: "已到账",
        };
        return stateMap[row.status];
      }
    },

    // 获取展开详情的接口
    async getOrderCommissionList(orderId) {
      this.infoLoadShow = true; //显示圈圈
      let result = await getOrderCommissionListApi({ orderId });
      if (result.code == 200) {
        this.infoLoadShow = false; //隐藏圈圈
        this.unfoldInfo = result.rows[0];
      }
    },

    // 获取资金明细的金额  有update_time就返回这个金额verify_amount
    getAmount(row) {
      if (row.update_time && row.update_time.length) {
        return row.verify_amount || row.amount;
      } else {
        return row.amount;
      }
    },

    // 专家分成如果有更新时间updateTime就显示withdrawAmount字段，没有就显示unfoldInfo.expertCommission
    getExpertAmount(row) {
      if (row.update_time && row.update_time.length) {
        return row.verify_amount;
      } else {
        return this.unfoldInfo.expertCommission;
      }
    },

    // ----------------------------------------资金账户----------------------------------------

    // ----------------------------------------提现----------------------------------------
    // 获取银行卡提现名称
    getWithName(item){
      if(item.type=='1'){
        return `${item.bank} (${item.cardNo.substring(item.cardNo.length - 4)})`
      }else if(item.type=='2'){
        return `微信(**${item.name.slice(-1)})`
      }else if(item.type=='3'){
        return `支付宝(${item.cardNo.substring(item.cardNo.length - 4)})`
      }
    },

    // 查询可提现金额
    async getMobileUserBalance(){
      let result = await getMobileUserBalanceApi()
      if(result.code==200){
        this.canwithdrawMoney = result.data
      }
    },

    // 当解绑了银行卡也要清空提现至的银行卡
    setWithdrawList(list) {
      this.withdraw.list = list;
      this.withdraw.bankcardId = list[0]?.id;
    },
    // 验证提现验证码
    async verifyObjFn() {
      if (this.verifyObj.code.length != 4) return;
      let { code } = await getVerificationCodeApi(this.verifyObj);
      if (code == 200) {
        this.verifyContentBtn = true;
        this.$message({
          type: "success",
          message: "验证通过",
        });
      } else {
        this.$message({
          type: "error",
          message: "验证码有误",
        });
      }
    },
    // 获取当前用户的角色
    async updateGetRoleIdFn() {
      // 这个接口开发时，后端人员比要忙，没有写接口文档
      let resutl = await updateGetRoleIdApi();
      if (resutl.code != 200) return;

      this.userRole = resutl;
    },

    // 获取提现订单
    async getOrderCommissionUserWithdrawalFn() {
      const { placeId, expertId, cmId } = this.userRole;
      const {pageNum,pageSize} = this.pageing

      let result = ''
      if(this.$store.state.user.roles.includes('swzy') || this.$store.state.user.roles.includes('qdzy')){
        // 商务和渠道调的接口
        result = await getCommercialManagerWithdrawalApi({pageNum,pageSize})
      }else if(this.$store.state.user.roles.includes('styyzj') || this.$store.state.user.roles.includes('stglry') || this.$store.state.user.roles.includes('stbbskr')){
        // 实体：实体运营总监、实体管理人员、实体拨比收款人 调的接口
        result = await getCommercialEntityWithdrawalApi({pageNum,pageSize})
      }else{
        // 专家调的接口
        result = await getExpertWithdrawalApi({pageNum,pageSize})
      }
      if (result.code != 200) return;
      this.WithdrawalList = [] //清空后重新获取
      let WithdrawalList = JSON.parse(JSON.stringify(result.rows)); 
      this.pageing.total = result.total
      this.WithdrawalList = [...this.WithdrawalList,...WithdrawalList]
      // 计算可用余额 toDecimal 保留两位小数(四舍五入)
      let avaBalance = 0;
      this.WithdrawalList.forEach((item) => {
        if (item.updateTime) {
          // 有更新时间
          if (item.withdrawAmount)
            avaBalance = amend(item.withdrawAmount, avaBalance);
        } else {
          // 无更新时间
          if (item.amount) avaBalance = amend(item.amount, avaBalance);
        }
      });
      // this.canwithdrawMoney = avaBalance;
      //$bus 重新查询可提现余额
      // this.$bus.$emit("getAvaBalance");
      return;

      // 过滤出没有提现的订单
      WithdrawalList = WithdrawalList.map((item) => {
        switch (Number(this.$store.state.user.userType)) {
          case 50:
            // 专家
            if (item.expertStatus == 0 && item.expertCommission != 0) {
              item.professional = "专家";
              return item;
            }

            break;
          case 60:
            // 商务
            for (const key in item) {
              if (item[key] == cmId) {
                switch (key) {
                  case "cmDirectorId":
                    item.professional = "商务经理";
                    break;
                  case "cmSupervisorId":
                    item.professional = "	商务总监";

                    break;
                  case "cmId":
                    item.professional = "	商务专员";

                    break;
                }

                // 商务专员没有提现过（状态为0）且提现的钱不等于0
                if (item.cmStatus == 0 && item.cmCommission != 0) {
                  return item;
                }
                // 除了商务专员没有提现过（状态为0）且提现的钱不等于0
                if (
                  item[key.slice(0, -2) + "Status"] == 0 &&
                  ![0, undefined, "", null].includes(item[key.slice(0, -2)])
                ) {
                  return item;
                }
              }
            }
            break;

          case 69:
            // 商务和渠道
            for (const key in item) {
              if (item[key] == cmId || item[key] == placeId) {
                switch (key) {
                  case "placeSupervisorId":
                    item.professional = "渠道总监";

                    break;
                  case "placeDirectorId":
                    item.professional = "渠道经理";

                    break;
                  case "placeId":
                    item.professional = "渠道专员";

                    break;
                  case "cmDirectorId":
                    item.professional = "商务经理";
                    break;
                  case "cmSupervisorId":
                    item.professional = "	商务总监";

                    break;
                  case "cmId":
                    item.professional = "	商务专员";

                    break;
                }
                // 商务专员没有提现过（状态为0）且提现的钱不等于0
                if (item.cmStatus == 0 && item.cmCommission != 0) {
                  return item;
                }
                // 渠道专员没有提现过（状态为0）且提现的钱不等于0
                if (item.placeStatus == 0 && item.placeCommission != 0) {
                  return item;
                }
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）并且截取调了就是钱的字段（不可以等于o）
                if (
                  item[key.slice(0, -2) + "Status"] == 0 &&
                  ![0, undefined, "", null].includes(item[key.slice(0, -2)])
                )
                  return item;
              }
            }
            break;
          case 65:
            // 渠道
            for (const key in item) {
              if (item[key] == placeId) {
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）
                switch (key) {
                  case "placeSupervisorId":
                    item.professional = "渠道总监";

                    break;
                  case "placeDirectorId":
                    item.professional = "渠道经理";

                    break;
                  case "placeId":
                    item.professional = "渠道专员";

                    break;
                }
                // 渠道专员没有提现过（状态为0）且提现的钱不等于0
                if (item.placeStatus == 0 && item.placeCommission != 0) {
                  return item;
                }
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）并且截取调了就是钱的字段（不可以等于o）
                if (
                  item[key.slice(0, -2) + "Status"] == 0 &&
                  ![0, undefined, "", null].includes(item[key.slice(0, -2)])
                )
                  return item;
              }
            }
            break;
        }
      });

      // 过滤undefined
      this.WithdrawalList = WithdrawalList.filter((item) => Boolean(item));

      this.canwithdrawMoney = this.WithdrawalList.reduce((prev, next) => {
        let Money = 0;
        switch (Number(this.$store.state.user.userType)) {
          case 50:
            // amend 是解决js进度错误问题

            return (prev = amend(prev, next.expertCommission));
          case 60:
            for (const key in next) {
              if (next[key] == cmId) {
                // 因为cmCommission 商务专员的拨比属性和 placeId 的不一样，所以截取掉id也不行
                if (key == "cmId") {
                  Money = amend(Money, next.cmCommission);
                  // Money = next.cmCommission;
                  continue;
                }

                Money = amend(Money, next[key.slice(0, -2)]);
                // Money += next[key.slice(0, -2)];
                // 把id截取掉，就是拨比key
              }
            }
            console.log(amend(prev, Money));
            return amend(prev, Money);
          // 商务和渠道
          case 69:
            console.log(next, placeId, cmId, "出来出来");
            for (const key in next) {
              if (next[key] == placeId || next[key] == cmId) {
                // 因为placeCommission 渠道专员的拨比属性和 placeId 的不一样，所以截取掉id也不行
                // 因为有多个角色所以要相加起来

                if (key == "placeId") {
                  Money = amend(Money, next.placeCommission);

                  // Money += next.placeCommission;
                  continue;
                }
                if (key == "cmId") {
                  Money = amend(Money, next.cmCommission);
                  // Money += next.cmCommission;
                  continue;
                }
                // console.log(next[key.slice(0, -2)]);
                if (next[key] == placeId || next[key] == cmId) {
                  // 把id截取掉，就是拨比key
                  // Money += next[key.slice(0, -2)];
                  Money = amend(Money, next[key.slice(0, -2)]);
                }
              }
            }
            return amend(prev, Money);
          case 65:
            for (const key in next) {
              if (next[key] == placeId) {
                if (key == "placeId") {
                  Money = amend(Money, next.placeCommission);
                  // Money += next.placeCommission;
                  continue;
                } // 因为placeCommission 渠道专员的拨比属性和 placeId 的不一样，所以截取掉id也不行

                // 把id截取掉，就是拨比key
                // Money = amend(prev,next[key.slice(0, -2)]);
                return amend(prev, next[key.slice(0, -2)]);
              }
            }
        }
      }, 0);

      this.withdraw.amount = "";
    },

    // 提现选择订单获取的所有钱总和
    GetAllMoney(allMoney, WithdrawalList) {
      this.withdraw.amount = allMoney;
      this.isOpenWithdrawOrder = false;
      this.withdrawalOrderList = WithdrawalList;
    },

    // 点击申请提现----------------------这里是申请提现------------------*******************
    clickWithdrawFn() {
      // 提现验证
      if (!this.withdraw.bankcardId) {
        this.$message({ type: "warning", message: "请选择银行卡" });
        return;
      }
      if (!this.verifyContentBtn) {
        this.$message({ type: "warning", message: "请先发送验证码" });
        return;
      }
      if (this.withdrawalOrderList.length < 1) {
        this.$message({ type: "warning", message: "请先选择提现订单" });
        return;
      }

      // 整理提现订单的id
      let orderId = [];
      this.withdrawalOrderList.forEach((item) => {
        orderId.push(item.id);
      });
      this.getOrderCommissionWithdraw(orderId);
    },

    // 申请提现的接口 防抖lodebounce
    getOrderCommissionWithdraw: lodebounce(async function(orderId){
      let data = {
        bankcardId: this.withdraw.bankcardId, //银行卡id
        orderId: orderId, //多个要提现的id
      };
      let result = await getOrderCommissionWithdrawApi(data);
      if (result.code == 200) {
        this.$message({ type: "success", message: "申请成功！" });

        this.WithdrawalList = [] //清空后重新获取
        this.getOrderCommissionUserWithdrawalFn(); //刷新列表
        this.getMobileUserBalance() //查询可提现金额
        //$bus 重新查询可提现余额
        this.$bus.$emit("getAvaBalance");
        // 清空数据
        this.verifyContentBtn = false;
        this.verifyObj.code = "";
        this.withdrawalOrderList = [];
        this.withdraw.amount = "";
      }
    },300),
    // 点击申请提现----------------------这里是申请提现------------------*******************end

    // 点击提现金额框 显示充值订单
    addWithdrawAmount() {
      this.getOrderCommissionUserWithdrawalFn();
      this.isOpenWithdrawOrder = true;
    },

    // 滚动到底部加载更多
    scrollLoadMore(){
      this.pageing.pageNum ++ 
      this.getOrderCommissionUserWithdrawalFn();
    },

    // 获取提现设置
    async getConfigWithdrawSettingFn() {
      let { code, data } = await getConfigWithdrawSettingApi();
      if (code != 200) return;
      const arr = ["w_min_money", "w_max_money"];
      data.forEach((item) => {
        if (arr.includes(item.type)) {
          this[item.type] = item.value;
        }
        console.log(this.w_max_money, "w_max_money");
      });
    },
    //   获取当前类型
    getSelectFn(item) {
      this.withdraw.bankCardId = item;
      //   console.log(item);
    },
    // 发送验证码
    async obtainVerifyCode() {
      // 防抖
      debounce(async () => {
        var self = this;
        if (self.verifyContent.disabled) {
          return;
        }
        if (self.validePhone()) {
          // 发送短信接口请求
          let { code } = await getOrderListApi(this.verifyObj.mobile);
          if (code != 200) return;
          self.countDown();
        }
      }, 500)();
    },
    // 倒计时方法
    countDown() {
      var time = 60;
      var timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.verifyContent.disabled = false;
          this.verifyContent.text = "获取验证码";
        } else {
          this.verifyContent.disabled = true;
          this.verifyContent.text = `重新获取(${time}s)`;
          time--;
          // this.verifyContent.time--;
        }
      }, 1000);
    },
    // 验证手机号
    validePhone() {
      console.log(!/^1[3456789]\d{9}$/.test(this.verifyObj.mobile));
      if (["", null, undefined].includes(this.verifyObj.mobile)) {
        this.$message({
          type: "warning",
          message: "请输入手机号",
        });
        return false;
      } else if (!/^1[3456789]\d{9}$/.test(this.verifyObj.mobile)) {
        this.$message({
          type: "warning",
          message: "请输入正确的手机号码",
        });
        return false;
      } else {
        return true;
      }
    },
    //申请提现
    async withdrawFn() {
      // 没发送验证码不给提现
      if (!this.verifyContentBtn) {
        this.$message({
          type: "warning",
          message: "请先发送验证码",
        });
        return;
      }
      const { placeId, expertId, cmId } = this.userRole;
      this.withdraw.list = this.withdrawalOrderList.map((item) => {
        switch (Number(this.$store.getters.userType)) {
          // 10自己注册 00系统注册 40跟单 50专家 60商务 65渠道 69商务和渠道 80实体 90专家助理
          case 50:
            if (Object.is(item.expertId, expertId) && item.expertStatus == 0) {
              return {
                // 1专家 2商务专员 3商务总监 4商务经理 5渠道专员 6渠道总监 7渠道经理
                type: 1,
                orderId: item.orderId,
              };
            }

            break;
          // 商务
          case 60:
            // 商务
            for (const key in item) {
              if (item[key] == cmId) {
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）
                if (item[key.slice(0, -2) + "Status"] == 0) {
                  let type = null;
                  switch (key) {
                    case "cmDirectorId":
                      type = 4;
                      break;
                    case "cmSupervisorId":
                      type = 3;
                      break;
                    case "cmId":
                      type = 2;
                      break;
                  }

                  return {
                    // 1专家 2商务专员 3商务总监 4商务经理 5渠道专员 6渠道总监 7渠道经理
                    type: type,
                    orderId: item.orderId,
                  };
                }
              }
            }
            break;
          case 65:
            // 渠道
            for (const key in item) {
              if (item[key] == placeId) {
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）
                if (item[key.slice(0, -2) + "Status"] == 0) {
                  let type = null;
                  switch (key) {
                    case "placeSupervisorId":
                      type = 6;
                      break;
                    case "placeDirectorId":
                      type = 7;
                      break;
                    case "placeId":
                      type = 5;

                      break;
                  }

                  return {
                    // 1专家 2商务专员 3商务总监 4商务经理 5渠道专员 6渠道总监 7渠道经理
                    type: type,
                    orderId: item.orderId,
                  };
                }
              }
            }
            break;

          case 69:
            //商务和渠道
            for (const key in item) {
              if (item[key] == placeId) {
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）
                if (item[key.slice(0, -2) + "Status"] == 0) {
                  let type = null;
                  switch (key) {
                    case "placeSupervisorId":
                      type = 6;
                      break;
                    case "placeDirectorId":
                      type = 7;
                      break;
                    case "placeId":
                      type = 5;

                      break;
                  }

                  return {
                    // 1专家 2商务专员 3商务总监 4商务经理 5渠道专员 6渠道总监 7渠道经理
                    type: type,
                    orderId: item.orderId,
                  };
                }
              }
              if (item[key] == cmId) {
                // 把id截取掉，就是拨比key+Status（判断当前订单状态是否为0）
                if (item[key.slice(0, -2) + "Status"] == 0) {
                  let type = null;
                  switch (key) {
                    case "cmDirectorId":
                      type = 4;
                      break;
                    case "cmSupervisorId":
                      type = 3;
                      break;
                    case "cmId":
                      type = 2;
                      break;
                  }

                  return {
                    // 1专家 2商务专员 3商务总监 4商务经理 5渠道专员 6渠道总监 7渠道经理
                    type: type,
                    orderId: item.orderId,
                  };
                }
              }
            }
            break;
        }
      });

      this.withdraw.list = this.withdraw.list.filter(Boolean);

      if (this.withdraw.list.length <= 0) {
        this.$message({
          type: "warning",
          message: "请选择提现的订单",
        });
        return;
      }

      let { code, msg } = await getIOrderCommissionWithdrawApi(this.withdraw);
      if (code != 200) return;

      this.$message({
        type: "success",
        message: msg,
      });
      this.withdraw.amount = "";
      this.verifyContentBtn = false;
      this.verifyObj.code = "";
      this.$refs.withDrawOrder.cleargetAllMoneyFn();
      return;
      // 定义变量
      const w_min_money = Number(this.w_min_money),
        w_max_money = Number(this.w_max_money),
        amount = Number(this.withdraw.amount);
      // 判断单笔是否小于或者超过提现最大与最小
      if (amount > this.amount) {
        this.$message({
          type: "warning",
          message: "余额不足",
        });
        return;
      }
      try {
        let { code } = await getIOrderCommissionWithdrawApi(this.verifyObj);
        if (code != 200) return;
      } catch (error) {
        this.$message({
          type: "warning",
          message: "请重新发送验证码",
        });
      }

      if (amount > w_max_money || amount < w_min_money) {
        this.$message({
          type: "warning",
          message: `单笔不可以${amount < w_min_money ? "小于" : "超过"}过${
            amount < w_min_money ? w_min_money : w_max_money
          }`,
        });
        return;
      }
      let type = this.$store.getters.userType;
      let withdrawResult;
      // 专家
      if (type == 50) {
        withdrawResult = await getExpertBrokerageAddApi(this.withdraw);
        // 商务
      } else {
        withdrawResult = await getCmBrokerageAddApi(this.withdraw);
      }

      if (withdrawResult.code != 200) return;
      this.$message({
        type: "success",
        message: withdrawResult.msg,
      });
      this.$emit(type == 50 ? "updateExpertDate" : "updateCmDate");
      //   更新数据
    },
  },
};
</script>

<style scoped>
/* --------------------------资金明细 ------------------------------*/
.detail {
  padding: 20px 30px;
}
.detail .el-form {
  border-bottom: 1px solid #efefef;
  margin-bottom: 20px;
}
::v-deep .detail .el-form-item__label {
  font-weight: 400;
  color: #999;
  font-size: 14px;
  line-height: 40px;
}
::v-deep .detail .el-input__prefix {
  left: auto;
  right: 5px;
}
::v-deep .detail .el-input__suffix {
  right: 20px;
}
::v-deep .detail .el-date-editor {
  width: 120px;
}
::v-deep .detail .el-input__inner {
  height: 40px;
  line-height: 40px;
  border-radius: 20px;
  padding: 0 15px;
}
::v-deep .detail .el-select {
  width: 120px;
}
::v-deep .detail .el-select .el-input__suffix {
  right: 5px;
}
.detail .inquire {
  border-color: #39486f;
  color: #39486f;
  font-weight: bold;
  font-size: 14px;
  padding: 12px 30px;
}
.detail .inquire:hover {
  background-color: #39486f;
  color: #fff;
}
.detail .isUp {
  color: #f87a23;
  font-weight: bold;
}
.detail .isDwon {
  color: #39486f;
  font-weight: bold;
}
.detail .el-table {
  margin-bottom: 50px;
}
::v-deep .detail .el-table .el-table__header-wrapper th,
::v-deep .detail .el-table .el-table__fixed-header-wrapper th {
  border: 0;
}
::v-deep .detail .el-table th.is-leaf,
::v-deep .detail .el-table td {
  border-bottom-color: #ecedf0;
  padding: 13px 0;
}
::v-deep .detail .el-table .expanded td {
  border-bottom: none;
}
::v-deep .detail .el-table td .el-table__expand-icon {
  text-align: right;
}
::v-deep .detail .el-table td .el-table__expand-icon > .el-icon {
  position: initial;
}
::v-deep
  .detail
  .el-table
  td
  .el-table__expand-icon
  .el-icon-arrow-right:before {
  content: "展开";
  font-size: 14px;
  color: #f87a23;
}
::v-deep .detail .el-table td .el-table__expand-icon--expanded {
  transform: rotate(0deg);
}
::v-deep
  .detail
  .el-table
  td
  .el-table__expand-icon--expanded
  .el-icon-arrow-right:before {
  content: "收起";
}
::v-deep .detail .el-table th.is-leaf .cell {
  color: #999;
}
::v-deep .detail .el-table .cell > p {
  margin: 0;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}
::v-deep .detail .el-table .cell > p.upp {
  color: #f87a23;
}
::v-deep .detail .el-table .cell > p.dwonp {
  color: #39486f;
}

::v-deep .detail .el-table .el-table__expanded-cell {
  padding-top: 0;
}
.orderDetail {
  padding: 10px;
  background-color: #f9fafd;
}

.orderDetail ul,
.orderDetail p,
.orderDetail h3 {
  margin: 0;
  padding: 0;
  list-style: none;
}
.orderDetail .noData-p {
  text-align: center;
  font-size: 12px;
  color: #999999;
  line-height: 24px;
}
.orderDetail h3 {
  font-size: 12px;
  font-weight: 600;
  color: #999999;
  line-height: 24px;
  margin-bottom: 5px;
}
.orderDetail ul {
  display: flex;
  flex-wrap: wrap;
}
.orderDetail ul > li {
  width: 20%;
  font-size: 12px;
  color: #999999;
  line-height: 24px;
}
.orderDetail > p {
  font-size: 12px;
  color: #999999;
  line-height: 24px;
}
/* 按钮样式 */
::v-deep .subBtn {
  padding: 20px 30px !important;
  justify-content: space-between;
  z-index: 99;
}
::v-deep .subBtn p {
  margin: 0;
  font-weight: bold;
  color: #333;
  font-size: 14px;
}
::v-deep .subBtn > .el-button.el-button--default {
  width: 100px;
  padding: 8px 0 !important;
  font-size: 14px;
  color: #f87a23;
  border-color: #f87a23;
}
::v-deep .subBtn > .el-button.addBtn {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}

/* -----------------------账户提现----------------------------- */
.withdraw {
  padding: 20px 30px;
}
.el-select-dropdown__item.selected {
  color: #f87a23;
}
::v-deep .withdraw .el-form-item__label {
  font-weight: 400;
  color: #666;
  font-size: 14px;
  line-height: 44px;
}
::v-deep .withdraw .el-form-item__content {
  line-height: 44px;
}
.withdraw .el-select {
  width: 100%;
}
::v-deep .withdraw .el-input__inner {
  height: 44px;
  line-height: 44px;
}
::v-deep .withdraw .el-input button {
  position: relative;
  border: 0;
  color: #f87a23;
  font-size: 14px;
}
::v-deep .withdraw .el-input button:focus,
::v-deep .withdraw .el-input button:hover {
  background-color: transparent;
}
::v-deep .withdraw .el-input button::before {
  content: "";
  position: absolute;
  left: 0;
  width: 1px;
  height: 12px;
  background-color: #d3d3d3;
}

.withdrawBtn {
  position: absolute;
  left: 0;
  bottom: 0;
  display: flex;
  justify-content: flex-end;
  width: 100%;
  padding: 10px 30px;
  border-top: 1px solid #ecedf0;
  background-color: #fff;
}
.withdrawBtn .el-button {
  padding: 0;
  width: 110px;
  padding: 10px 0;
  font-weight: bold;
  color: #999;
}
.withdrawBtn .el-button.addBtn {
  border-color: #f87a23;
  background-color: #f87a23;
  color: #fff;
}
.withdrawBtn .el-button:hover {
  border-color: #f87a23;
  color: #f87a23;
  background-color: transparent;
}
.withdrawBtn .el-button.addBtn:hover {
  border-color: #f87a23;
  background-color: #f87a23;
  color: #fff;
  opacity: 0.9;
}
.withdrawBtn .el-button.canwithdraw {
  border-color: #999;
  background-color: #999;
  cursor: not-allowed;
}
.withdrawBtn .el-button.canwithdraw:hover {
  border-color: #999;
  background-color: #999;
  color: #fff;
  opacity: 0.9;
}
</style>
